package com.liu.quartz;

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

import java.util.MissingResourceException;
import java.util.ResourceBundle;

/**
 * @Author: hc
 * @Date: 2019/10/22 16:41
 */
public class AutoUpdateQuartzService {

	private AutoUpdateQuartzService() {

	}

	private static AutoUpdateQuartzService aus = null;

	/**
	 * 制作单例
	 *
	 * @return
	 */
	public static AutoUpdateQuartzService getInstance() {
		if (aus == null) {
			aus = new AutoUpdateQuartzService();
		}
		return aus;
	}

	/**
	 * 启动自动更新程序监听
	 */
	public void startAutoListener() {
		ResourceBundle resb = ResourceBundle.getBundle("app");
		try {
			String mycron = resb.getString("systemupdate.autoupdate.mycron");
			System.out.println("任务监听时间:" + mycron);
			addAutoUpdateTask(mycron, "mytask");
		} catch (MissingResourceException e) {
			System.out.println("获取定时任务时间异常");
		}
	}

	/**
	 * 添加定时系统监听任务
	 */
	private void addAutoUpdateTask(String cron, String type) {
		if (cron == "") {
			return;
		}
		SchedulerFactory sf = new StdSchedulerFactory();
		Scheduler scheduler = null;
		JobDetail job = null;
		CronTrigger cronTrigger = null;
		String cronTriggerName = type + "autoupdatejob";
		String TRIGGER_GROUP_NAME = "TRIGGERGROUP_TIMESCHE" + type.toUpperCase();
		String jobName = type + "autoupdatejob";
		String JOB_GROUP_NAME = "JOBGROUP_TIMESCHE" + type.toUpperCase();
		try {
			scheduler = sf.getScheduler();
			cronTrigger = TriggerBuilder.newTrigger().withIdentity(cronTriggerName, TRIGGER_GROUP_NAME)
					.withSchedule(CronScheduleBuilder.cronSchedule(cron).withMisfireHandlingInstructionDoNothing())
					.build();
			/* 获取 job 任务类 */
			// 1.clazz：job 实现类
			// 2. jobName： 任务名
			// 3. JOB_GROUP_NAME：任务组名
			// 4. job：任务
			if ("mytask".equals(type)) {
				job = JobBuilder.newJob(AutoMyUpdateQuartzTask.class).withIdentity(jobName, JOB_GROUP_NAME).build();
			}
			scheduler.scheduleJob(job, cronTrigger);
			if (!scheduler.isShutdown()) {
				scheduler.start();
			}
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
	}

}